import * as echarts from 'echarts';
import dayjs from 'dayjs'; 

export function renderSunChart(domElement, sunrise, sunset, currentTime) {
  if (!domElement) return console.error('DOM元素不存在');
  
  const myChart = echarts.init(domElement);
  
  // 计算时间轴（日出到日落的小时刻度）
  const timeAxis = getHourTicks(sunrise, sunset);
  
  // 模拟太阳高度数据
  const heightData = getHeightData(timeAxis.length, sunrise, sunset);
  
  // 计算当前时间点
  const currentPoint = getRealTimePoint(sunrise, sunset, currentTime);

  // ECharts 配置项
  const option = {
    title: { 
      text: '日出日落时间',
      left: 'center'
    },
    grid: {
      top: '10%',
      left: '10%',
      right: '20%',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: timeAxis,
      axisLabel: { 
        formatter: (val) => {
          const sunriseTime = dayjs(sunrise, 'HH:mm').format('HH:mm');
          const sunsetTime = dayjs(sunset, 'HH:mm').format('HH:mm');
          const sunriseHour = sunriseTime.split(':')[0];
          const sunsetHour = sunsetTime.split(':')[0];
          return val === sunriseHour ? sunriseTime : (val === sunsetHour ? sunsetTime : '');
        }
      }
    },
    yAxis: {
      type: 'value',
      name: '高度角（°）',
      max: 90,
      min: 0
    },
    series: [
      {
        name: '太阳轨迹',
        type: 'line',
        data: heightData,
        smooth: 0.6,
        symbol: 'none',
        lineStyle: { color: '#ff7f0e' },
        areaStyle: { color: 'rgba(255, 127, 14, 0.2)' }
      },
      {
        name: '当前位置',
        type: 'scatter',
        data: currentPoint ? [currentPoint] : [],
        symbolSize: 20,
        itemStyle: { 
          color: '#ff4d4f',
          emphasis: {
            color: '#ff0000',
            borderColor: '#000',
            borderWidth: 2
          }
        },
        emphasis: {
          scale: 1.5
        }
      }
    ]
  };

  myChart.setOption(option);
  
  return {
    dispose: () => myChart.dispose()
  };
}

  // 5. 工具函数（提取到独立逻辑）
  /** 生成日出到日落的小时刻度 */
  function getHourTicks(sunrise, sunset) {
    const startHour = dayjs(sunrise, 'HH:mm').hour();
    const endHour = dayjs(sunset, 'HH:mm').hour();
    const ticks = [];
    for (let h = startHour; h <= endHour; h++) {
      ticks.push(h.toString().padStart(2, '0'));
    }
    return ticks;
  }

  /** 模拟太阳高度数据（正弦曲线） */
  function getHeightData(length, sunrise, sunset) {
    const sunriseTime = dayjs(sunrise, 'HH:mm');
    const sunsetTime = dayjs(sunset, 'HH:mm');
    const totalHours = sunsetTime.diff(sunriseTime, 'hour');
    
    return Array.from({ length }, (_, i) => {
      const progress = i / (length - 1);
      return 90 * Math.sin(progress * Math.PI);
    });
  }

  /** 计算当前时间在图表中的位置 */
  function getRealTimePoint(sunrise, sunset, currentTime) {
    const now = dayjs(currentTime);
    const sunriseTime = dayjs(sunrise, 'HH:mm');
    const sunsetTime = dayjs(sunset, 'HH:mm');

    // 不在日出日落区间，返回 null
    if (now.isBefore(sunriseTime) || now.isAfter(sunsetTime)) {
      return null;
    }

    const totalHours = sunsetTime.diff(sunriseTime, 'hour');
    const elapsedHours = now.diff(sunriseTime, 'hour');
    const progress = elapsedHours / totalHours;

    const timeAxis = getHourTicks(sunrise, sunset);
    const xIndex = Math.min(timeAxis.length - 1, Math.floor(progress * timeAxis.length));
    const height = 90 * Math.sin(progress * Math.PI);

    return [timeAxis[xIndex], height];
  }